package com.fjl;

import org.apache.ibatis.executor.statement.StatementHandler;
import org.apache.ibatis.plugin.*;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.sql.Connection;
import java.util.Properties;

@Intercepts({@Signature(type = StatementHandler.class, method = "prepare", args = {Connection.class, Integer.class})})
@Component
public class MyBatisQueryTimeInterceptor implements Interceptor {

    @Value("${abpm.sql.sqlOutTime:30}")
    int sqlOutTime;
    @Override
    public Object intercept(Invocation invocation) throws Throwable {
        long startTime = System.currentTimeMillis();
        Object result = invocation.proceed();
        long endTime = System.currentTimeMillis();
        long duration = endTime - startTime;

        if (duration > sqlOutTime) {  // 记录超过 1ms的查询
           LogUtil.error("Slow SQL detected: " + invocation.getMethod() + " executed in " + duration + " ms");
        }

        return result;
    }

    @Override
    public Object plugin(Object target) {
        return Plugin.wrap(target, this);
    }

    @Override
    public void setProperties(Properties properties) {
        // No properties needed
    }
}
